# -*- coding: utf-8 -*-
from rest_framework.views import exception_handler as drf_exception_handler
import logging
from django.db import DatabaseError
from redis.exceptions import RedisError
from rest_framework.response import Response
from rest_framework import status
from .exception_type import *

error_logger = logging.getLogger("error")
info_logger = logging.getLogger("info")


def exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 异常
    :param context: 抛出异常的上下文
    :return: Response响应对象
    """
    # 调用drf框架原生的异常处理方法
    response = drf_exception_handler(exc, context)
    # response为None表示drf框架里面没有这样的异常，此时来寻找我们定义的异常逻辑
    if response is None:
        view = context['view']
        # 如果是数据库异常或者是redis异常，都会去处理，这里就是自定义异常逻辑处理
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            # 数据库异常
            error_logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误', "status": "fail"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

        elif isinstance(exc, Exception400):
            info_logger.error('[%s] %s' % (view, exc))
            response = Response({"message": exc.args[0], "status": "fail"}, status=status.HTTP_400_BAD_REQUEST)

        elif isinstance(exc, Exception200):
            info_logger.error('[%s] %s' % (view, exc))
            response = Response({"message": exc.args[0], "status": "fail"}, status=status.HTTP_200_OK)

        elif isinstance(exc, Exception500):
            error_logger.error('[%s] %s' % (view, exc))
            response = Response({"message": exc.args[0], "status": "fail"},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return response
